import logging


from core.constant import Offset



class OrderManagement:
    def __init__(self, **kwargs):
        self.logger = logging.getLogger('check_order')

        # 一次报单最小开仓限制
        self.once_min_open_vol_limit = kwargs.get('min_open_vol_limit', {})
        self.once_max_open_vol_limit = kwargs.get('once_max_open_vol_limit', {})

        #
        # # 一次报单最小开仓限制
        # self.once_min_open_vol_limit = global_variable.get_value('min_open_vol_limit', load_json=True)
        # # 一次报单最大开仓手数限制
        # self.once_max_open_vol_limit = global_variable.get_value('once_max_open_vol_limit', load_json=True)

    # 把标的 UR405.CZCE 转换为UR.CZCE
    def re_vt_symbol(self, vt_symbol):
        import re
        re_vt_symbol = re.sub(r'\d+', '', vt_symbol).upper()
        return re_vt_symbol

    # 检查订单的条件
    def check_order(self, vt_symbol, offset, volume):
        try:
            # 检查最大下单手数
            volume = self.check_max_vol_limit(vt_symbol, volume)
            # 开仓逻辑限制。
            if offset == Offset.OPEN:
                self.logger.debug(
                    f'start check, offset open check vt_symbol:{vt_symbol},offset:{offset},volume:{volume}')
                # 检查最小开仓限制
                min_vol_limit_bool = self.check_min_limit_vol(vt_symbol, volume)
                self.logger.debug(
                    f'end check, result vt_symbol:{vt_symbol},offset:{offset},min_vol_limit_bool:{min_vol_limit_bool},volume:{volume}')
                return min_vol_limit_bool, volume
            # 不是开仓。不做逻辑处理
            return False, volume
        except Exception as e:
            import traceback
            traceback.print_exc()
            info = traceback.format_exc()
            self.logger.error(e, info)

    # 获取限制标的手数
    def check_min_limit_vol(self, vt_symbol, volume):
        vol_limit = self.once_min_open_vol_limit
        # 先检查有没有具体合约存在
        if vt_symbol in vol_limit:
            self.logger.debug(f'vt_symbol{vt_symbol},volume:{volume},return:{volume < vol_limit[vt_symbol]}')
            return volume < vol_limit[vt_symbol]
        # 检查有没有标的设置
        vt_symbol = self.re_vt_symbol(vt_symbol)
        if vt_symbol in vol_limit:
            self.logger.debug(f'vt_symbol{vt_symbol},volume:{volume},return:{volume < vol_limit[vt_symbol]}')
            return volume < vol_limit[vt_symbol]
        return False

    # 检查一次最大开仓手数
    def check_max_vol_limit(self, vt_symbol, volume):
        self.logger.debug(f'vt_symbol:{vt_symbol},volume:{volume}')
        check_volume = self.get_max_vol(vt_symbol, volume)
        if volume == check_volume:
            vt_symbol = self.re_vt_symbol(vt_symbol)
            return self.get_max_vol(vt_symbol, volume)
        else:
            return check_volume

    def get_max_vol(self, vt_symbol, volume):
        if vt_symbol not in self.once_max_open_vol_limit:
            return volume

        if self.once_max_open_vol_limit.get(vt_symbol, 0) < self.once_min_open_vol_limit.get(vt_symbol, 0):
            self.logger.error(
                f'limit config error。max_vol_limit :{self.once_max_open_vol_limit.get(vt_symbol)} < min_vol_limit :{self.once_min_open_vol_limit.get(vt_symbol)}')
            return 0
        # 交易手数小于最大手数，直接用交易手数，反之
        if volume < self.once_max_open_vol_limit.get(vt_symbol, 0):
            new_vol = volume
        else:
            new_vol = self.once_max_open_vol_limit.get(vt_symbol)
        self.logger.debug(
            f'vt_symbol:{vt_symbol},volume:{volume},max_vol_limit:{self.once_max_open_vol_limit.get(vt_symbol)},new_volume:{new_vol}')
        return new_vol


# if __name__ == '__main__':
#     from scripts.base_task import BaseTask
#     account_name = 'test_simnow01'
#     config=BaseTask(account_name=account_name).config_json
#     min_open_vol_limit=config.get('min_open_vol_limit')
#     once_max_open_vol_limit=config.get('once_max_open_vol_limit')
#
#     order_management = OrderManagement(min_open_vol_limit=min_open_vol_limit,once_max_open_vol_limit=once_max_open_vol_limit)
#     # 开仓检查通过
#     # min_vol_limit_bool
#     # 开仓
#     min_vol_limit_bool, volume = order_management.check_order("RM505.CZCE", Offset.OPEN, 3)
#     assert (min_vol_limit_bool and volume == 3)
#     min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.OPEN, 4)
#     assert (~min_vol_limit_bool and volume == 4)
#     min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.OPEN, 7)
#     assert (~min_vol_limit_bool and volume == 7)
#     # 平仓
#     min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.CLOSE, 3)
#     assert (~min_vol_limit_bool and volume == 3)
#     min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.CLOSE, 4)
#     assert (~min_vol_limit_bool and volume == 4)
#     min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.CLOSE, 7)
#     assert (~min_vol_limit_bool and volume == 7)
#
#     # min_vol_limit_bool, volume = order_management.check_order("UR401.CZCE", Offset.CLOSE, 7)
#     # assert (~min_vol_limit_bool and volume == 8)
#     # print(min_vol_limit_bool, volume)
